// pages/song/song.js
var song = wx.createInnerAudioContext()
Page({

  data: {
    play: true,
    //播放音频的下标
    audioIndex: 0,
    //播放音频在滑动器的进度
    progress: 0,
    //播放音频在滑动器的最大进度
    duration: 0,
  },

  onLoad: async function (options) {
    var id = options.id;
    var module = await import("../../utils/http");
    var res = await module.MusicHttp.songUrl(id);
    var url;
    res.data.data.forEach(item => {
      url = item.url
    })
    var picUrl = wx.getStorageSync('url');
    var tracks = wx.getStorageSync('tracks');
    this.setData({ picUrl, tracks });
    song.src = url;
    this.countTime(song);
    song.play();
  },
  pause() {
    var play = !this.data.play;
    this.setData({ play });
    this.handlePlay(play);
  },
  countTime(song){
    var play = this.data.play;
    if(play){
      setTimeout(() => {
        this.setData({
          progress: Math.ceil(song.currentTime),
          progressText: this.formatTime(Math.ceil(song.currentTime)),
          duration: Math.ceil(song.duration),
          durationText: this.formatTime(Math.ceil(song.duration))
        })
        this.countTime(song);
      },);
    }
  },
  formatTime(s){
    let t = '';
    s = Math.floor(s);
    if (s > -1) {
      let min = Math.floor(s / 60) % 60;
      let sec = s % 60;
      if (min < 10) {
        t += "0";
      }
      t += min + ":";
      if (sec < 10) {
        t += "0";
      }
      t += sec;
    }
    return t;
  },
  sliderChange(e) {
    //获取滑动条的值
     var value = e.detail.value;
     //先暂停播放
    //  song.pause();
     //把文件的播放点改成滑动条的值
     song.seek(value);//.seek()文件从头开始的偏移量
     this.setData({
       //把播放的时间设置为滑动条的值
       progressText: this.formatTime(value)
     })
    //  song.play();
   },
  handlePlay(play) {
    if (play) {
      song.play();
      this.countTime(song);
    } else if (!play) {
      song.pause();
    }
  }
})